<?php

/**
 * Login class.
 * Login is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class Login extends CFormModel {
	public $email;
	public $senha;
	public $verifyCode;

	private $_identity;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules() {
        return array(
            // username and password are required
            array('email', 'required', 'message' => 'Digite um email válido'),
            array('senha', 'required', 'message' => 'Digite uma senha válida'),
            // verifyCode needs to be entered correctly
            array('verifyCode', 'required', 'message' => 'Digite um código válido', 'on' => Yii::app()->captcha->getScenarioNameCaptchaRequired()),
            array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'message' => 'Digite o código correto', 'on' => Yii::app()->captcha->getScenarioNameCaptchaRequired()),
            // password needs to be authenticated
            array('senha', 'authenticate'),
        );
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels() {
        return array(
            'email' => 'E-mail',
            'senha' => 'Senha',
            'verifyCode' => 'Verification Code',
        );
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute, $params) {
        if(!$this->hasErrors()) {
            $this->_identity = new UserIdentity($this->email, $this->senha);
            $this->_identity->authenticate();

            switch($this->_identity->errorCode) {
                case UserIdentity::ERROR_NONE:
                    Yii::app()->user->login($this->_identity);
                    break;
                case UserIdentity::ERROR_USERNAME_INVALID:
                    $this->addError('email', 'E-mail inexistente');
                    break;
                default: // UserIdentity::ERROR_PASSWORD_INVALID
                    $this->addError('senha', 'Senha incorreta');
                    break;
            }
        }
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login() {
        if($this->_identity === null) {
            $this->_identity = new UserIdentity($this->email, $this->senha);
            $this->_identity->authenticate();
        }
        if($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
            $duration = 0;
            Yii::app()->user->login($this->_identity, $duration);
            return true;
        }
        else
            return false;
	}
}
